package com.easyoffer.common.util;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.easyoffer.common.BaseResponse;
import com.easyoffer.common.ErrorCode;
import com.easyoffer.constant.UserConstant;
import com.easyoffer.exception.BusinessException;
import com.easyoffer.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.concurrent.TimeUnit;

/**
 * 网络工具类
 *
 */
@Component
@Slf4j
public class NetUtils {
    @Resource
    private CountUtils countUtils;

    /**
     * 获取客户端 IP 地址
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1")) {
                // 根据网卡取本机配置的 IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (inet != null) {
                    ip = inet.getHostAddress();
                }
            }
        }
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        if (ip == null) {
            return "127.0.0.1";
        }
        return ip;
    }

    /**
     *  获取设备类型
     * @param userGentInfo UserAgent的值
     * @return 设备类型 PC/APP
     */
    public static String getDeviceType(String userGentInfo) {
        UserAgent userAgent = UserAgentUtil.parse(userGentInfo);
        System.out.println( "brower" +  userAgent.getBrowser());
        System.out.println( "os" +  userAgent.getOs());
        boolean mobile = userAgent.isMobile();
        if (mobile)
            return "APP";
        else
            return "PC";
    }

    /**
     * 判断是否为爬虫,有风险进行警告
     * @param key 登录用户id
     * @return true为爬虫
     */
    public boolean crawlerDetect(String key){
        // 调用多少次时告警
        final int WARN_COUNT = 10;
        // 超过多少次封号
        final int BAN_COUNT = 20;
        //用户一分钟内访问次数
        long visitCount = countUtils.incrAndGetCounter(key, 1, TimeUnit.MINUTES,180);
        // 每分钟访问 WARN_COUNT 次则告警
        if (visitCount == WARN_COUNT){
            log.warn("用户 {} 访问次数 {}", key, visitCount);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "警告访问过于频繁");
        }
        //每分钟访问超过 BAN_COUNT 次则封号
        if (visitCount >= BAN_COUNT){
            return true;
        }
        return false;
    }

}
